<template>
  <div id="pay-insurance-info-confirm">

    <div class="public-footer-btn-box" @click="updateInfo">
      <button class="single-button" :disabled="submitDisabled">确定</button>
    </div>

    <fill-owner-info
      type="part"
      :info="ownerInfo"
      :editable="false"
      @isOwnerPersonType="isOwnerPersonType"
      @updateIdCard="modifyIdCard"
      v-if="infoReady"></fill-owner-info>

    <fill-car-info
      ref="comp-car-info"
      type="part"
      :info="carInfo"
      :editable="false"
      @updateCertification="modifyCertification"
      v-if="infoReady"></fill-car-info>

    <fill-insurance-policy
      ref="compInsurancePolicy"
      type="part"
      :info="policyInfo"
      :editable="false"
      @updateNeedEvidence="modifyNeedEvidence"
      @updateReceiverName="modifyReceiverName"
      @updateReceiverTel="modifyReceiverTel"
      @updateReceiverAddress="modifyReceiverAddress"
      v-if="infoReady"></fill-insurance-policy>
  </div>
</template>

<script>
  import FillOwnerInfo from './comp-fill-owner-info.vue';
  import FillCarInfo from './comp-fill-car-info.vue';
  import FillInsurancePolicy from './comp-fill-insurance-policy.vue';
  import { Indicator, Toast } from 'mint-ui';
  export default {
    name: "pay-insurance-info-confirm",
    components: {
      FillOwnerInfo,
      FillCarInfo,
      FillInsurancePolicy
    },
    data() {
      return {
        ownerInfo: {},
        carInfo: {},
        policyInfo: {},
        infoReady: false,
        submitDisabled: false,
        car_owner_id: '',
        car_id: '',
        policy_id: '',
        order_id: ''
      }
    },
    methods: {
      modifyIdCard(url, type) {
        if (type === 'idFrontImg') {
          this.ownerInfo.idFront = url;
        } else if (type === 'idBackImg') {
          this.ownerInfo.idBack = url;
        }
      },
      modifyCertification(url, type, index) {
        this.carInfo[type][index] = url;
      },
      modifyNeedEvidence(newValue) {
        this.policyInfo.needEvidence = newValue;
      },
      modifyReceiverName(newValue) {
        this.policyInfo.receiverName = newValue;
      },
      modifyReceiverTel(newValue) {
        this.policyInfo.receiverTel = newValue;
      },
      modifyReceiverAddress(newValue) {
        this.policyInfo.receiverAddress = newValue;
      },
      // 更改信息
      updateInfo() {
        this.$validator.validateAll().then((result) => {
          if (result) {
            if (!this.ownerInfo.idFront || !this.ownerInfo.idBack) {
              let msg = +this.ownerInfo.ownerType === 1 ? '请上传身份证' : '请上传营业执照';
              return Toast(msg);
            } else if ((this.$route.params.type === 'add' || this.$route.params.type === 'continue') && (!this.carInfo.licence[0] || !this.carInfo.licence[1])) {
              return Toast('请上传行驶证');
            } else if (this.$route.params.type === 'new' && (!this.carInfo.evidence[0] || !this.carInfo.evidence[1])) {
              return Toast('请上传合格证及发票');
            } else if (this.policyInfo.needEvidence === '1' && (!this.policyInfo.receiverName || !this.policyInfo.receiverTel || this.$refs.compInsurancePolicy.receiverLocation === '请选择-请选择-请选择' || !this.$refs.compInsurancePolicy.formOne.aboutPlace.blocks)) {
              return Toast('请完善保单邮寄信息');
            } else {
              this.$http.post({
                api: this.$api.INSURANCE_INFO_CONFIRM,
                params: {
                  car_owner_id: {
                    car_owner_type: this.ownerInfo.ownerType,

                    name: this.ownerInfo.name,
                    num: this.ownerInfo.idNum,
                    end_date: this.ownerInfo.idEffectTime,
                    phone: this.ownerInfo.tel,
                    address: this.ownerInfo.address,
                    linkman: this.ownerInfo.contact,
                    sex: this.ownerInfo.contactGender,
                    id_card_face: this.ownerInfo.idFront,
                    id_card_back: this.ownerInfo.idBack,
                    user_id: localStorage.getItem('id'),

                    // 新增时 必传 (有行驶证)

                    plate_num: this.ownerInfo.licence,
                    plate_num_type: this.ownerInfo.licenceType,

                    // 修改时 必传 (有行驶证)

                    car_owner_id: this.car_owner_id
                  },
                  car_id: {
                    car_owner_id: this.car_owner_id,

                    /**
                     * 表单一
                     */
                    model: (this.carInfo.carBrand).replace('牌', ''),
                    provice: this.carInfo.place,
                    traffic: this.carInfo.type,
                    vin: (this.carInfo.carNum).toUpperCase(),
                    engine_num: (this.carInfo.carEngineNum).toUpperCase(),
                    buy_time: this.carInfo.date,
                    car_nature: this.carInfo.usage,
                    is_local: this.carInfo.locale,
                    nature: this.carInfo.belong,
                    transfer: this.carInfo.newly,
                    transfer_date: this.carInfo.carTransferDate,
                    mortgage: this.carInfo.mortgage,
                    beneficiary: this.carInfo.beneficiary,
                    scale: this.carInfo.benefitProportion,
                    special_agreement: this.carInfo.specially,

                    taxes_type: this.carInfo.taxesTypeCode,
                    taxes_reason: this.carInfo.taxesReductionReasonCode,
                    taxes_code: this.carInfo.taxesReductionReasonCodeLong,
                    taxes_organ: this.carInfo.taxesDepartment,
                    taxes_program: this.carInfo.taxesReductionPlanCode,
                    taxes_no: this.carInfo.taxesNo,
                    taxes_amount: this.carInfo.taxesReduction,
                    taxes_proportion: this.carInfo.taxesReductionRate || 0,
                    fuel_type: this.carInfo.energyCode,

                    /**
                     * 表单二
                     */
                    insured: this.carInfo.recognizeeSameAsOwner,

                    // 被保人信息（非必传）

                    insured_name: this.carInfo.recognizeeSameAsOwner === '1' ? '' : this.carInfo.recognizee,
                    insured_num: this.carInfo.recognizeeSameAsOwner === '1' ? '' : this.carInfo.recognizeeIdNum,
                    insured_phone: this.carInfo.recognizeeSameAsOwner === '1' ? '' : this.carInfo.recognizeeTel,

                    policy_holder: this.carInfo.applicant,

                    // 投保人信息（非必传）

                    policy_name: this.carInfo.applicantName,
                    policy_num: this.carInfo.applicantIdNum,
                    policy_phone: this.carInfo.applicantTel,

                    /**
                     * 表单三
                     */

                    car_url: this.carInfo.pictures,
                    remark: this.carInfo.others,
                    certificate_url: this.carInfo.evidence[0],
                    invoice: this.carInfo.evidence[0],

                    // 有车牌时必传（修改）

                    car_id: this.car_id,
                    driving_face: this.carInfo.licence[0],
                    driving_back: this.carInfo.licence[1],
                    invoice2: this.carInfo.licence[2]
                  },
                  policy_id: {
                    car_owner_id: this.car_owner_id,
                    car_id: this.car_id,
                    user_id: localStorage.getItem('id'),

                    /**
                     * 表单一
                     */
                    is_get: this.policyInfo.needEvidence,
                    mail: this.policyInfo.byMail,
                    name: this.policyInfo.receiverName,
                    phone: this.policyInfo.receiverTel,
                    address: this.policyInfo.receiverAddress,

                    /**
                     * 表单二
                     */
                    is_immefc: this.policyInfo.effectTiming,
                    start_time: this.policyInfo.insuranceEffectDate,
                    hours: this.policyInfo.advancedInsuranceEffectTime,

                    jq_is_immefc: this.policyInfo.jqEffectTiming,
                    jq_start_time: this.policyInfo.jqInsuranceEffectDate,
                    jq_hours: this.policyInfo.jqAdvancedInsuranceEffectTime,

                    // 修改时必传
                    policy_id: this.policy_id
                  }
                },
                success: (res) => {
                  this.confirmPolicy();
                }
              });
            }
          }
        });
      },
      // 人工核保页面
      enterAuditingPage() {
        this.$router.push({
          path: '/tip/1',
          query: {
            company_id: this.$route.params.company_id,
            order_id: this.order_id
          }
        });
      },
      // 核保失败页面
      enterFailPage(msg) {

        // sessionStorage 保存核保失败原因

        sessionStorage.setItem('failureReason', msg);

        this.$router.push('/tip/2');
      },
      confirmPolicy() {

        this.submitDisabled = true;
        Indicator.open({
          text: '核保中...',
          spinnerType: 'snake'
        });

        this.$http.post({
          api: this.$api.INSURANCE_POLICY_CONFIRM,
          params: {
            order_id: this.order_id,
            company_id: this.$route.params.company_id
          },

          // 支付二维码

          success: (res) => {
            Indicator.close();
            this.$router.push({
              name: 'PayInsuranceFinal',
              params: {
                company_id: this.$route.params.company_id,
                order_id: this.order_id,
                order_pay_id: res.data.msg.qrcode.order_pay_id
              },
              query: {
                num: res.data.msg.people.plate_num,
                price: res.data.msg.price,
                code: res.data.msg.qrcode.url
              }
            })
          },

          failure: (res) => {
            Indicator.close();

            if (res.data.error_msg) {

              // 报错

              this.enterFailPage(res.data.error_msg);
            } else {

              // 常规跳转至人工核保页面

              this.enterAuditingPage();
            }
          },

          error: () => {
            Indicator.close();
            Toast('网络错误');
            this.submitDisabled = false;
          }
        })
      },
      isOwnerPersonType(val) {
        this.$refs['comp-car-info'].formTwo.recognizeeIdNumLabel = +val === 1 ? '被保人身份证号' : '社会信用代码';
        this.$refs['comp-car-info'].formTwo.applicantIdNumLabel = +val === 1 ? '投保人身份证号' : '社会信用代码';
      }
    },
    created() {
      this.$http.post({
        api: this.$api.INSURANCE_DETAIL_CONFIRM,
        params: {
          model_id: this.$route.query.model_id,
          in_id: this.$route.query.in_id,
          user_id: localStorage.getItem('id'),
          company_id: this.$route.params.company_id
        },
        success: (res) => {
          this.order_id = res.data.data.order_id;
          this.$http.post({
            api: this.$api.INSURANCE_INFO_CONFIRM,
            params: {
              order_id: res.data.data.order_id
            },
            success: (res) => {
              let info = res.data.data;

              this.ownerInfo = {
                ownerType: info.car_owner_type,

                name: info.name,
                idNum: info.num,
                idEffectTime: info.end_date,
                licence: info.plate_num,
                licenceType: info.plate_num_type,
                tel: info.phone,
                address: info.address,
                contact: info.linkman,
                contactGender: info.sex,
                idFront: info.id_card_face,
                idBack: info.id_card_back
              };

              this.carInfo = {
                carBrand: info.model,
                place: info.provice,
                type: info.traffic,
                carNum: info.vin,
                carEngineNum: info.engine_num,
                date: info.buy_time || '请选择-请选择-请选择',
                usage: info.car_nature,
                locale: info.is_local,
                belong: info.nature,
                newly: info.transfer,
                carTransferDate: info.transfer_date,
                mortgage: info.mortgage,
                beneficiary: info.beneficiary,
                benefitProportion: info.scale,
                specially: info.special_agreement,

                taxesTypeCode: info.taxes_type,
                taxesReductionReasonCode: info.taxes_reason,
                taxesReductionReasonCodeLong: info.taxes_code,
                taxesDepartment: info.taxes_organ,
                taxesReductionPlanCode: info.taxes_program,
                taxesNo: info.taxes_no,
                taxesReduction: info.taxes_amount,
                taxesReductionRate: info.taxes_proportion,
                energyCode: info.fuel_type,

                recognizeeSameAsOwner: info.insured,
                recognizee: info.insured_name,
                recognizeeIdNum: info.insured_num,
                recognizeeTel: info.insured_phone,
                applicant: info.policy_holder,
                applicantName: info.policy_name,
                applicantIdNum: info.policy_num,
                applicantTel: info.policy_phone,

                pictures: info.car_url,
                others: info.remark,

                evidence: [info.certificate_url, info.invoice],

                licence: [info.driving_face, info.driving_back, info.invoice2]
              };

              this.policyInfo = {
                needEvidence: info.is_get,
                byMail: info.mail,
                receiverName: info.iname,
                receiverTel: info.iphone,
                receiverAddress: info.iaddress,
                storageReceiverAddress: info.iaddress,

                effectTiming: info.is_immefc,
                insuranceEffectDate: info.start_time,
                advancedInsuranceEffectTime: info.hours,

                jqEffectTiming: info.jq_is_immefc,
                jqInsuranceEffectDate: info.jq_start_time,
                jqAdvancedInsuranceEffectTime: info.jq_hours
              };

              this.car_owner_id = info.car_owner_id;
              this.car_id = info.car_id;
              this.policy_id = info.policy_id;

              this.infoReady = true;
            }
          });
        }
      });
    }
  }
</script>

<style scoped lang="scss">


  #pay-insurance-info-confirm {
    padding-bottom: $public-footer-btn-box-height;
  }
</style>
